import { Node } from "@tiptap/core";

const FileNode = Node.create({
  name: "linkcard",

  group: "block",
  selectable: true,
  atom: true,

  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML: (element) => {
          const linkEl = element.querySelector(".skc-link");
          return linkEl ? linkEl.textContent : null;
        },
      },
      src: {
        default: null,
        parseHTML: (element) => {
          const imgEl = element.querySelector("img");
          return imgEl ? imgEl.getAttribute("src") : null;
        },
      },
      text: {
        default: null,
        parseHTML: (element) => {
          const textEl = element.querySelector(".skc-text");
          return textEl ? textEl.textContent : null;
        },
      },
    };
  },

  parseHTML() {
    return [
      {
        tag: "div.skc-link-card", // 匹配 class="skc-link-card" 的 div
        getAttrs: (node) => {
          if (node && node.nodeType === 1 && node.tagName === "DIV" && node.classList.contains("skc-link-card")) {
            const imgElement = node.querySelector("img");
            const src = imgElement?.getAttribute("src");

            const textElement = node.querySelector(".skc-text");
            const text = textElement?.textContent?.trim();

            const hrefElement = node.querySelector(".skc-link");
            const href = hrefElement?.textContent?.trim();

            if (src && text && href) {
              return {
                src,
                text,
                href,
              };
            }
          }
          return false;
        },
      },
    ];
  },

  renderHTML({ HTMLAttributes }) {
    const { href, src, text } = HTMLAttributes;

    return [
      "div",
      {
        class: "skc-link-card",
      },
      [
        "div",
        {},
        ["img", { src }],
      ],
      [
        "div",
        { class: "skc-text-box" },
        ["span", { class: "skc-text" }, text],
        ["span", { class: "skc-link" }, href],
      ],
    ];
  },
});

export default FileNode;
